package com.example.demo.config;

import com.example.demo.util.TokenUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("进入拦截器了");
        //中间写逻辑代码，比如判断是否登录成功，失败则返回false
        String uri = request.getRequestURI();
        System.out.println("当前路径"+uri);

        /**
         * HandlerMethod=>Controller中标注@RequestMapping的方法
         *  需要配置静态资源不拦截时，添加这块逻辑  => 前后端分离项目
         */
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String token=request.getHeader("token");
        String username=request.getHeader("username");
        System.out.println("token:"+token);

        if (!(TokenUtil.verify(token)&&TokenUtil.getUser(token).getUsername().equals(username))) {
            // 未登录跳转到登录界面
            System.out.println("no login!!!!!");
//            throw  new RuntimeException("no login!");
            return false;
        } else {
            return true;
        }
//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        //
        System.out.println("controller 执行完了");
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("获取到了一个返回的结果："+response);
        System.out.println("请求结束\n");
    }
}
